import org.junit.Test;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;


public class ClientSocket implements ISocket {
    private InetAddress server_address;
    private static final String TAG = "SocketClient";
    private Exception exception = null;
    private byte[] date;
    private DatagramSocket client;
    private DatagramPacket rePacket = new DatagramPacket(new byte[BUFF_SIZE], BUFF_SIZE);

    public Exception getException() {
        return exception;
    }

    public ClientSocket() {


    }

    public void send() {
        try {

            client = new DatagramSocket();
            server_address = InetAddress.getByName(SERVER_ADDRESS);
            DatagramPacket packet = new DatagramPacket(date, date.length, server_address, PORT);
            client.setSoTimeout(5000);
            client.send(packet);
            client.receive(rePacket);
        } catch (UnknownHostException e) {
            exception = e;
        } catch (SocketException e) {
            exception = e;
        } catch (IOException e) {
            exception = e;
        }
    }

    public void close() {
        if (null != client) client.close();
    }
@Test
public void test(){
        login(null,null);
}
    @Override
    public void login(DatagramPacket packet,String[] datas) {//全部传递null，参数服务器需要，本地不需要
        fillData(LOGIN, "123", "2143");
        send();
        if (exception == null) {
            String str = new String(rePacket.getData(),rePacket.getOffset(),rePacket.getLength());
            System.out.println(str);
        }
    }

    private void fillData(int what, String... datas) {
        byte[] bWhat = ISocket.intToByteArray(what);
        int length = bWhat.length;
        for (String d : datas) {
            length += (d + ISocket.TAG).getBytes().length;
        }
        this.date = new byte[length];
        int pos = bWhat.length;
        System.arraycopy(bWhat, 0, this.date, 0, bWhat.length);
        for (String d : datas) {
            byte[] b_data = (d + ISocket.TAG).getBytes();
            System.arraycopy(b_data, 0, this.date, pos, b_data.length);
            pos+=b_data.length;
        }
    }
}
